package cn.xfdtool.slowsql.listener.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.xfdtool.slowsql.dto.SlowSQLDTO;
import cn.xfdtool.slowsql.dto.SlowSQLNotifyDTO;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;

/**
 * 简单慢SQL数据解析
 *
 * @author xfd
 * 2022/5/14
 */
@Slf4j
public class SimpleSlowSQLParserListener extends AbstractSlowSQLParserListener {

    @Override
    protected SlowSQLNotifyDTO doParse(SlowSQLDTO slowSQLDTO) throws Throwable {
        final Object[] args = slowSQLDTO.getInvocation().getArgs();
        final MappedStatement ms = (MappedStatement)args[0];
        final Object param = args[1];
        final BoundSql boundSql = ms.getBoundSql(param);
        final String sql = boundSql.getSql();
        final Object paramObject = boundSql.getParameterObject();

        // 构建返回值
        SlowSQLNotifyDTO.SlowSQLNotifyDTOBuilder builder = SlowSQLNotifyDTO.builder();
        builder.parseSuccess(Boolean.TRUE)
                .methodName(ms.getId())
                .args(paramObject)
                .execTime((slowSQLDTO.getEnd() - slowSQLDTO.getStart()))
                .resultRowCount(parseResultRowCount(slowSQLDTO.getResult()))
                .prepareSQL(sql)
                .throwable(slowSQLDTO.getThrowable())
                .extProps(slowSQLDTO.getExtProps())
        ;
        if (ObjectUtil.isEmpty(slowSQLDTO.getThrowable())) {
            // 慢SQL(考虑这里try起来, 容错)
            builder.execSQL(replacePrepareParam(sql, slowSQLDTO.getInvocation()));
        }
        return builder.build();
    }
}
